import time
import json
from xiaopy import *
from cotc import COTC

try:
    ui = xp.ui()
    region = ui.stringValue("region")
    targeting_npc = ui.stringValue("targeting_npc")
    round_per_recover = int(ui.stringValue("round_per_recover"))
    use_previous_battle_sequence = ui.boolValue("use_previous_battle_sequence")
    if use_previous_battle_sequence:
        with open('bt_battle_sequence.txt', 'r') as f:
            battle_sequence = json.loads(f.read())
    else:
        battle_sequence_string = ui.stringValue("battle_sequence").replace(" ", "").replace("\n", "")
        battle_sequence = json.loads(battle_sequence_string)
        with open('bt_battle_sequence.txt', 'w') as f:
            f.write(battle_sequence_string)
    c = COTC(region)
except Exception as e:
    xp.toast(e)


def run_script():
    total_count = 0
    while True:
        total_count += 1
        xp.log("第" + str(total_count) + "轮")
        start_time = time.time()

        # 战斗前
        c.move_towards_bt_npc(targeting_npc)

        for i in range(round_per_recover):
            c.inquire_and_impress_bt_npc(targeting_npc)
            c.await_black_screen_transition()

            # 战斗中
            xp.log("第" + str(i+1) + "场")
            # c.flee_battle()
            c.run_preset_battle_sequence(battle_sequence)
            c.tap_until_minimap_show(c.cst.close_menu_btn_coord)

            # 战斗后
            c.open_party()
            c.open_allies_list()
            c.part_ways_ally(targeting_npc)

        c.move_using_worldmap(c.cst.screen_center_coord)
        c.await_black_screen_transition()
        c.tap_inn_on_main_screen(c.cst.get_town_name_by_npc[targeting_npc])
        c.await_black_screen_transition()
        c.recover_in_inn(c.cst.get_town_name_by_npc[targeting_npc])
        c.move_using_minimap(c.cst.inn_exit_coord[c.cst.get_town_name_by_npc[targeting_npc]])
        c.await_black_screen_transition()

        xp.log("本轮用时：" + str(int(time.time() - start_time)) + "秒")
        xp.log("------------------------")


run_script()
